import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { APP_CONFIG } from '@/configs'

// 路由配置

// 路由表
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/pages/Login.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/pages/Register.vue'),
    meta: {
      title: '注册',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Home',
    component: () => import('@/pages/Home.vue'),
    meta: {
      title: '任务列表',
      requiresAuth: true
    }
  },
  {
    path: '/my-day',
    name: 'MyDay',
    component: () => import('@/pages/MyDay.vue'),
    meta: {
      title: '我的一天',
      requiresAuth: true
    }
  },
  {
    path: '/task/:id',
    name: 'TaskDetail',
    component: () => import('@/pages/TaskDetail.vue'),
    meta: {
      title: '任务详情',
      requiresAuth: true
    }
  },
  {
    path: '/groups',
    name: 'GroupManage',
    component: () => import('@/pages/GroupManage.vue'),
    meta: {
      title: '分组管理',
      requiresAuth: true
    }
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/pages/NotFound.vue'),
    meta: {
      title: '页面不存在',
      requiresAuth: false
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由拦截
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = `${to.meta.title || 'Todo管理系统'} - ${APP_CONFIG.NAME}`

  // 检查是否需要认证
  const requiresAuth = to.meta.requiresAuth !== false
  
  // 从本地存储中获取认证状态，而不是直接使用store
  const token = localStorage.getItem('todo_token')
  const userInfo = localStorage.getItem('todo_user_info')
  const isAuthenticated = !!token && !!userInfo

  if (requiresAuth && !isAuthenticated) {
    // 需要认证但未登录，跳转到登录页
    next('/login')
  } else if (!requiresAuth && isAuthenticated && to.path === '/login') {
    // 已登录且访问登录页，跳转到首页
    next('/')
  } else {
    // 其他情况，正常跳转
    next()
  }
})

export default router
